import { Drawer, Flex, Button } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { React, useState, useEffect } from 'react'
import { copyText } from '../../../utils/indx'
import { Diff } from 'diff'
import * as sqlFormatter from 'sql-formatter'

const ConfigDiff = (props) => {
    const { isDrawOpen = false, config: configData, datasourceType, onClose,onSave } = props
    const [config, $config] = useState('')
    const [formatConfig, $formatConfig] = useState('')
    const [diff, $diff] = useState('')

    const formatJSONFn = (configStr) => {
        const jsonObj = JSON.parse(configStr);
        const prettyJson = JSON.stringify(jsonObj, null, 2);
        return prettyJson;
    }

    const formatSQLFn = (configStr) => {
        return sqlFormatter.format(configStr);
    }

    const formatFn = (configStr) => {
        if (Number(datasourceType) === 1) {
            return formatSQLFn(configStr)
        } else {
            return formatJSONFn(configStr)
        }
    }

    useEffect(() => {
        console.log('xxxxxxx', configData);
        
        if (configData) {
            $formatConfig(formatFn(configData))
        }else{
            $formatConfig('')
        }
        $config('')
    }, [configData])


    const formCurrentConfig = (str) => {
        $config(formatFn(str))
    }

    // useEffect(() => {
    //     console.log(configData, config);
    //     if (configData && config) {
    //         const diff = new Diff();
    //         const diffObj = diff.diff(configData, config);
    //         const diffStr = diffObj.map(part => {
    //             const color = part.added ? 'green' :
    //                 part.removed ? 'red' : 'grey';
    //             return `<span style="color: ${color}">${part.value}</span>`;
    //         })
    //             .join('');
    //         $diff(diffStr)
    //     }
    // }, [config, configData])

    const _onSave = () => {
        onSave(config)
        // 保存
        onClose()
    }


    return (<Drawer placement='left' open={isDrawOpen} onClose={onClose} width={800} zIndex={1000} footer={
        <Flex>
            <Button onClick={onClose}>取消</Button>
            <Button type='primary' onClick={_onSave}>保存</Button>
        </Flex>
    }>
        <Flex justify="space-between" gap={20}>
            <Button onClick={() => copyText(formatConfig)} disabled={!formatConfig || formatConfig?.length === 0}>一键复制</Button>
            <Button onClick={() =>config && formCurrentConfig(config)}>格式化</Button>
        </Flex>
        <Flex justify="space-between" gap={20}>
            {configData && <TextArea value={formatConfig} disabled={true} style={{ height: 'calc(100vh - 150px)' }} />}
            <TextArea value={config} onChange={(e) => $config(e.target.value)} style={{ height: 'calc(100vh - 150px)' }} />
        </Flex>
    </Drawer>)
}

export default ConfigDiff;